package cn.sciento.farm.devicemanager.dao.config;

import cn.sciento.farm.devicemanager.common.util.BaseContextHandler;
import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.StringValue;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * User: wumu
 * Date: 11/12/17
 * Time: 7:04 PM
 */
@Configuration
@MapperScan("cn.sciento.farm.devicemanager.dao.mapper*")
public class MybatisPlusConfig {

    Logger logger = LoggerFactory.getLogger(getClass());


    private Map<String,Boolean> tableMap =new ConcurrentHashMap();


    private List<String> filterTable = Arrays.asList(
            "dev_collection_type"
    );

    private boolean isSkip(String tableName){
        Boolean en = tableMap.get(tableName);
        if(en == null){
            for(int i =0;i<filterTable.size();i++){
                if(tableName.matches(filterTable.get(i))){
                    tableMap.put(tableName,true);
                    return true;
                }
            }
            tableMap.put(tableName,false);
            return false;
        }else {
            return en;
        }
    }


    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
//    @Profile("dev")
//    @Bean
//    public PerformanceInterceptor performanceInterceptor() {
//        return new PerformanceInterceptor();
//    }

    /**
     * mybatis-plus分页插件<br>
     * 文档：http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//        paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的支持
        paginationInterceptor.setDialectType("mysql");
        /*
         * 【测试多租户】 SQL 解析处理拦截器<br>
         * 这里固定写成住户 1 实际情况你可以从cookie读取，因此数据看不到 【 麻花藤 】 这条记录（ 注意观察 SQL ）<br>
         */
        List<ISqlParser> sqlParserList = new ArrayList<>();
        SensorTenantSqlParser sensorTenantSqlParser = new SensorTenantSqlParser();
        sensorTenantSqlParser.setTenantHandler(new TenantHandler() {
            @Override
            public Expression getTenantId() {
                if(BaseContextHandler.isNull()){
                    return null;
                }
                String tenantId = BaseContextHandler.getTenantId();
                logger.info("拦截器的租客ID:{}",tenantId);
                if(tenantId == null){
                    return null;
                }
                return new StringValue(tenantId);
            }

            @Override
            public String getTenantIdColumn() {
                return "tenant_id";
            }

            @Override
            public boolean doTableFilter(String tableName) {
                boolean en = isSkip(tableName);
                logger.info("判断过滤的表名字:{}{}", tableName,en);
                // 这里可以判断是否过滤表
                return en;
            }
        });
        sqlParserList.add(sensorTenantSqlParser);
        paginationInterceptor.setSqlParserList(sqlParserList);
//        paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() {
//            @Override
//            public boolean doFilter(MetaObject metaObject) {
//                MappedStatement ms = PluginUtils.getMappedStatement(metaObject);
//                // 过滤自定义查询此时无租户信息约束【 麻花藤 】出现
//                if ("com.baomidou.springboot.mapper.UserMapper.selectListBySQL".equals(ms.getId())) {
//                    return true;
//                }
//                return false;
//            }
//        });
        return paginationInterceptor;
    }

}